<template>
    <view class="container">
        <view class="content" @touchstart="hideDrawer">
            <scroll-view class="msg-list" :scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" :scroll-into-view="scrollToView" upper-threshold="50">
                <!-- 加载历史数据waitingUI -->
                <view class="loading">
                    <view v-bind:class="{ spinnerhide: isSpinnerhide, spinner: isSpinner }">
                        <view class="rect1"></view>
                        <view class="rect2"></view>
                        <view class="rect3"></view>
                        <view class="rect4"></view>
                        <view class="rect5"></view>
                    </view>
                </view>
                <view
                    v-if="msgList != undefined && msgList != ''"
                    class="row u-m-l-20 u-m-r-20"
                    v-for="(row, index) in msgList"
                    :key="index"
                    :id="row.msg != undefined ? 'msg' + row.msg.chatId : ''"
                >
                    <view v-if="row.type != ''" class="u-m-b-20">
                        <!-- 系统消息 -->
                        <block v-if="row.type == 'system'">
                            <view class="system">
                                <!-- 文字消息 -->
                                <view v-if="row.msg.type == 'text'" class="text">
                                    <view style="display: flex;align-items: center;word-wrap:break-word;flex-wrap: wrap;" v-html="row.msg.content.text"></view>
                                </view>
                            </view>
                        </block>
                        <!-- 用户消息 -->
                        <block v-if="row.type == 'chat'">
                            <!-- 自己发出的消息 -->
                            <view class="my" v-if="row.msg.from == userinfo.id">
                                <!-- 左-消息 -->
                                <view class="left">
                                    <view class="username">
                                        <view class="time">{{ row.msg.time }}</view>
                                    </view>
                                    <!-- 文字消息 -->
                                    <view v-if="row.msg.type == 'text'" class="bubble">
                                        <rich-text style="display: flex;align-items: center;word-wrap:break-word;flex-wrap: wrap;" :nodes="row.msg.content"></rich-text>
                                    </view>
                                    <!-- 语言消息 -->
                                    <view v-if="row.msg.type == 'voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.chatId ? 'play' : ''">
                                        <view class="length">{{ row.msg.content.length }}</view>
                                        <view class="icon my-voice"></view>
                                    </view>
                                    <!-- 图片消息 -->
                                    <view v-if="row.msg.type == 'img'" class="bubble img" @tap="showPic(row.msg)">
                                        <image :src="row.msg.content.url" :style="{ width: row.msg.content.w + 'px', height: row.msg.content.h + 'px' }"></image>
                                    </view>
                                </view>
                                <!-- 右-头像 -->
                                <view class="right chat-avatar" @click="toHomePage(row.msg.from)">
                                    <image :src="logoMask" mode="aspectFill"></image>
                                    <text class="u-line-1">{{ row.msg.fromName }}</text>
                                </view>
                            </view>
                            <!-- 别人发出的消息 -->
                            <view class="other" v-if="row.msg.from != undefined && row.msg.from != userinfo.id">
                                <!-- 左-头像 -->
                                <view class="left chat-avatar" @click="toHomePage(row.msg.from)">
                                    <text class="u-line-1">{{ row.msg.fromName }}</text>
                                    <image :src="logoMask" mode="aspectFill"></image>
                                </view>
                                <!-- 右-用户名称-时间-消息 -->
                                <view class="right">
                                    <view class="username">
                                        <view class="time">{{ row.msg.time }}</view>
                                    </view>
                                    <!-- 文字消息 -->
                                    <view v-if="row.msg.type != 'goods'">
                                        <view v-if="row.msg.type == 'text'" class="bubble">
                                            <rich-text style="display: flex;align-items: center;word-wrap:break-word;flex-wrap: wrap;" :nodes="row.msg.content"></rich-text>
                                        </view>
                                    </view>
                                    <!-- 语音消息 -->
                                    <view v-if="row.msg.type == 'voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.chatId ? 'play' : ''">
                                        <view class="icon other-voice"></view>
                                        <view class="length">{{ row.msg.content.length }}</view>
                                    </view>
                                    <!-- 图片消息 -->
                                    <view v-if="row.msg.type == 'img'" class="bubble img" @tap="showPic(row.msg)">
                                        <image
                                            :src="row.msg.content.url + '?imageView2/2/w/350'"
                                            :style="{ width: row.msg.content.w + 'px', height: row.msg.content.h + 'px' }"
                                        ></image>
                                    </view>
                                </view>
                            </view>
                        </block>
                    </view>
                </view>
            </scroll-view>
        </view>
        <!-- 抽屉栏 -->
        <view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
            <!-- 表情 -->
            <swiper class="emoji-swiper" :class="{ hidden: hideEmoji }" indicator-dots="true" duration="150">
                <swiper-item v-for="(page, pid) in emojiList" :key="pid">
                    <view v-for="(em, eid) in page" :key="eid" @tap="addEmoji(em)"><image mode="widthFix" :src="'../../static/img/emoji/' + em.url"></image></view>
                </swiper-item>
            </swiper>
            <!-- 更多功能 相册-拍照-红包 -->
            <view class="more-layer" :class="{ hidden: hideMore }">
                <view class="list">
                    <view class="box" @tap="chooseImage"><view class="icon tupian2"></view></view>
                    <view class="box" @tap="camera"><view class="icon paizhao"></view></view>
                    <!-- <view class="box voice">
						<view class="icon" :class="isVoice ? 'jianpan' : 'yuyin'" @tap="switchVoice"></view>
					</view> -->
                </view>
            </view>
        </view>
        <!-- 底部输入栏 -->
        <view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
            <view class="textbox">
                <view
                    class="voice-mode"
                    :class="[isVoice ? '' : 'hidden', recording ? 'recording' : '']"
                    @touchstart="voiceBegin"
                    @touchmove.stop.prevent="voiceIng"
                    @touchend="voiceEnd"
                    @touchcancel="voiceCancel"
                >
                    {{ voiceTis }}
                </view>
                <view class="text-mode" :class="isVoice ? 'hidden' : ''">
                    <view class="box"><textarea auto-height="true" v-model="textMsg" @focus="textareaFocus" /></view>
                    <view class="em" @tap="chooseEmoji"><image style="width:48rpx;height:48rpx;" src="../../static/HM-chat/face.png"></image></view>
                </view>
            </view>
            <view class="more" @tap="showMore"><image style="width:48rpx;height:48rpx;" src="../../static/HM-chat/add.png"></image></view>
            <view class="send" :class="isVoice ? 'hidden' : ''" @tap="sendText"><view class="btn">发送</view></view>
        </view>

        <!-- 录音UI效果 -->
        <view class="record" :class="recording ? '' : 'hidden'">
            <view class="ing" :class="willStop ? 'hidden' : ''"><view class="icon luyin2"></view></view>
            <view class="cancel" :class="willStop ? '' : 'hidden'"><view class="icon chehui"></view></view>
            <view class="tis" :class="willStop ? 'change' : ''">{{ recordTis }}</view>
        </view>
        <u-toast ref="uToast" />
    </view>
</template>
<script>
import { emoji } from '@/config/emoji.js';
import utils from '@/common/utils.js';

export default {
    data() {
        return {
            isGroup: true,
            groupId: '',
            toUserId: '',
            type: 1,
            teamId: '',
            //右侧弹窗
            logoMask: this.$mAssetsPath.logoMask,
            userinfo: this.$store.state.userInfo,
            //文字消息
            goodsData: {},
            product: {},
            textMsg: '',
            scrollAnimation: false,
            scrollTop: 0,
            scrollToView: '',
            msgList: [],
            msgImgList: [],
            msgloalhost: [],
            myuid: 0,
            isSpinnerhide: true,
            isSpinner: false,
            //录音相关参数
            // #ifndef H5
            //H5不能录音
            RECORDER: uni.getRecorderManager(),
            // #endif
            isVoice: false,
            voiceTis: '按住 说话',
            recordTis: '手指上滑 取消发送',
            recording: false,
            willStop: false,
            initPoint: { identifier: 0, Y: 0 },
            recordTimer: null,
            recordLength: 0,

            //播放语音相关参数
            AUDIO: uni.createInnerAudioContext(),
            playMsgid: null,
            VoiceTimer: null,
            // 抽屉参数
            popupLayerClass: '',
            // more参数
            hideMore: true,
            //表情定义
            hideEmoji: true,
            emojiList: emoji,

            loading: false,
            msg_Storage_key: '',
            unReadMsgNum: []
        };
    },
    onReady() {
        uni.hideTabBar();
    },
    onLoad(option) {
        //语音自然播放结束
        this.AUDIO.onEnded(res => {
            this.playMsgid = null;
        });
        // #ifndef H5
        //录音开始事件
        this.RECORDER.onStart(e => {
            this.recordBegin(e);
        });
        //录音结束事件
        this.RECORDER.onStop(e => {
            this.recordEnd(e);
        });
        // #endif
        var that = this;
        that.msgList = [];

        //获取离线消息
        if (this.$store.state.is_open_socket) {
            this.$store.commit('WEBSOCKET_SEND', JSON.stringify({ type: 'offline_chat' }));
        }

        uni.$on('websocket-message-process', res => {
            const { code, type } = JSON.parse(res.data);
            if (res.data != {}) var msgData = JSON.parse(res.data);
            if (type == 'chat' || type == 'offline_chat') {
                this.updateMessage();
            }
        });

        //请求离线消息
        //this.$store.commit('WEBSOCKET_SEND', JSON.stringify({ type: 'offline_chat'})); //发送当前聊天窗口信息
    },
    onShow() {
        const tmpMsgId = uni.getStorageSync('tmpMsgId');

        this.toUserId = tmpMsgId;
        this.isGroup = false;
        this.toType = 0;

        if (JSON.stringify(this.$store.state.userInfo) == '{}') {
            uni.redirectTo({
                url: '../login/login'
            });
        } else {
            if (this.userinfo.id != this.$store.state.userInfo.id) {
                if (this.toUserId == this.$store.state.userInfo.id) this.toUserId = '';
                this.userinfo = this.$store.state.userInfo;
            }
        }
        this.$store.commit('SET_TOMSGUSERID', this.toUserId);
        this.updateMessage();
        // #ifdef APP-PLUS
        uni.hideTabBar();
        // #endif
    },
    mounted() {
        let token = uni.getStorageSync('token');
        // 检查链接情况
        this.connectSocketInit();
    },
    methods: {
        updateMessage() {
            if (!this.userinfo?.id && this.toUserId) {
                return;
            }

            let msg = utils.getMessage('gMsgList' + '-' + userId + '-' + `cs_${this.toUserId}`);

            this.msgList = msg;
            this.$nextTick(() => {
                this.goToBottom(99999);
            });
        },
        toHomePage(id) {
            uni.navigateTo({
                url: '../authorization/homepage?id=' + id
            });
        },
        connectSocketInit() {
            var that = this;
            if (JSON.stringify(this.$store.state.is_open_socket) != '{}' && this.$store.state.is_open_socket) {
                that.screenMsg({ type: 'system', msg: { id: 0, type: 'text', content: { text: '欢迎使用智汇方舟系统' } } });
            }
        },
        // 接受消息(筛选处理)
        async screenMsg(msg) {
            if (msg != undefined) {
                //从长连接处转发给这个方法，进行筛选处理
                if (msg.type == 'system') {
                    // 系统消息
                    switch (msg.msg.type) {
                        case 'text':
                            this.addSystemTextMsg(msg);
                            break;
                    }
                } else if (msg.type == 'goods') {
                    // 商品消息
                    switch (msg.msg.type) {
                        case 'text':
                            this.addTextMsg(msg);
                            break;
                    }
                } else if (msg.type == 'chat') {
                    // 用户消息
                    switch (msg.msg.type) {
                        case 'text':
                            this.addTextMsg(msg);
                            break;
                        case 'notice':
                            this.addTextMsg(msg);
                            break;
                        case 'HB':
                            this.addTextMsg(msg);
                            break;
                        case 'voice':
                            this.addVoiceMsg(msg);
                            break;
                        case 'img':
                            this.addImgMsg(msg);
                            break;
                        case 'goods':
                            let goodsData = await this.$apis.goodsinfo({
                                id: msg.msg.content.text
                            });
                            if (goodsData.status == 1) {
                                this.product = goodsData.result.goods;
                            }
                            this.addTextMsg(msg);
                            break;
                    }
                    //非自己的消息震动
                    if (msg.msg.to != this.myuid) {
                        uni.vibrateLong();
                    }
                }
                var that = this;
                this.$nextTick(function() {
                    // 滚动到底
                    that.goToBottom(99999);
                    if (msg.msg != undefined) {
                        this.scrollToView = 'msg' + msg.msg.chatId;
                    }
                });
            }
        },

        /*
			发送消息处理
		*/
        sendMsgloalhost(msgData) {
            let list = [];

            if (msgData != undefined && JSON.stringify(msgData) != '{}') {
                msgData.msg.sendTime = this.$mUtils.getDateTime();

                //推送给聊天窗口
                list = msgData;
                list.msg.time = this.$mUtils.formatTimeMD(list.msg.sendTime);
                if (list.type == 'chat' && list.msg.type == 'img') {
                    list.msg.content = this.setPicSize(list.msg.content);
                    this.msgImgList.push(list.msg.content.url);
                }

                utils.handleMessage(list);
                this.updateMessage();

                //聊天窗口自动滚动到底部
                // setTimeout(() => {
                //     this.$nextTick(() => {
                //         //进入页面滚动到底部
                //         this.goToBottom(99999);
                //         this.$nextTick(() => {
                //             this.scrollAnimation = true;
                //         });
                //     });
                // }, 150);
                this.isSpinnerhide = true;
                this.isSpinner = false;
            }
        },
        /*接收socket数据*/
        // getMsgloalhost(myuid, receiveId, msgData, groupType) {
        //     var that = this,
        //         roomId = '',
        //         list = [],
        //         teamId = '',
        //         msgloalhost = { dataList: [] };
        //     if (receiveId && JSON.stringify(receiveId).indexOf('_') != -1) {
        //         roomId = 'group_' + receiveId + '_' + this.userinfo.id;
        //     } else {
        //         if (myuid != '' && receiveId != '') {
        //             if (myuid < receiveId) {
        //                 roomId = myuid + '_' + receiveId;
        //             } else {
        //                 roomId = receiveId + '_' + myuid;
        //             }
        //         }
        //     }

        //     if (roomId != '' && groupType != undefined) {
        //         let arrgroupType = groupType.split('_');
        //         let type = arrgroupType[0];
        //         if (receiveId != '' && JSON.stringify(receiveId).indexOf('_') != -1) {
        //             let tids = receiveId.split('_');
        //             teamId = tids[1];
        //         }
        //         if (receiveId != '' && JSON.stringify(receiveId).indexOf('_') == -1) {
        //             teamId = arrgroupType[1];
        //         }

        //         var msg_Storage_key = type + '_' + teamId + '_' + roomId;
        //         that.msg_Storage_key = msg_Storage_key;
        //         if (uni.getStorageSync('msgloalhost_' + msg_Storage_key) != '') msgloalhost = uni.getStorageSync('msgloalhost_' + msg_Storage_key);

        //         if (msgData != undefined && JSON.stringify(msgData) != '{}') {
        //             //聊天存本地
        //             if (msgloalhost.dataList.length > 0) {
        //                 var len = msgloalhost.dataList.length >= 1 ? msgloalhost.dataList.length - 1 : msgloalhost.dataList.length;
        //                 if (msgloalhost.dataList[len] != undefined && msgData.msg.chatId != msgloalhost.dataList[len].msg.chatId) msgloalhost.dataList.push(msgData);
        //             } else {
        //                 msgloalhost.dataList.push(msgData);
        //             }
        //             uni.setStorageSync('msgloalhost_' + msg_Storage_key, msgloalhost || {});
        //         }

        //         var nowMyuid = this.$store.state.userInfo.id,
        //             nowReceiveId = this.toUserId,
        //             nowRoomId = '';
        //         if (nowMyuid < nowReceiveId) {
        //             nowRoomId = nowMyuid + '_' + nowReceiveId;
        //         } else {
        //             nowRoomId = nowMyuid + '_cs_' + nowReceiveId;
        //         }

        //         var now_teamId = this.type == 999 ? 999 : this.teamId; //当前群组
        //         var now_key = '';
        //         if (that.isGroup) {
        //             now_key = now_key = this.type + '_' + now_teamId + '_' + 'group_' + that.groupId + '_' + nowMyuid;
        //         } else {
        //             now_key = this.type + '_' + now_teamId + '_' + nowRoomId;
        //         }

        //         if (now_key == msg_Storage_key) {
        //             //推送给聊天窗口
        //             list = msgData;
        //             list.msg.time = this.$mUtils.formatTimeMD(list.msg.sendTime);
        //             if (list.type == 'chat' && list.msg.type == 'img') {
        //                 list.msg.content = that.setPicSize(list.msg.content);
        //                 that.msgImgList.push(list.msg.content.url);
        //             }

        //             that.msgList.push(list);

        //             //聊天窗口自动滚动到底部
        //             setTimeout(() => {
        //                 that.$nextTick(function() {
        //                     //进入页面滚动到底部
        //                     that.goToBottom(99999);
        //                     that.$nextTick(function() {
        //                         that.scrollAnimation = true;
        //                     });
        //                 });
        //             }, 150);
        //             that.isSpinnerhide = true;
        //             that.isSpinner = false;
        //         }
        //     }
        // },
        //处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
        setPicSize(content) {
            // 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
            let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
            let maxH = uni.upx2px(350); //350是定义消息图片最大高度
            if (content.w > maxW || content.h > maxH) {
                let scale = content.w / content.h;
                content.w = scale > 1 ? maxW : maxH * scale;
                content.h = scale > 1 ? maxW / scale : maxH;
            }
            return content;
        },

        //更多功能(点击+弹出)
        showMore() {
            this.isVoice = false;
            this.hideEmoji = true;
            if (this.hideMore) {
                this.hideMore = false;
                this.openDrawer();
            } else {
                this.hideDrawer();
            }
        },
        // 打开抽屉
        openDrawer() {
            this.popupLayerClass = 'showLayer';
        },
        // 隐藏抽屉
        hideDrawer() {
            this.popupLayerClass = '';
            setTimeout(() => {
                this.hideMore = true;
                this.hideEmoji = true;
            }, 150);
        },
        // 选择图片发送
        chooseImage() {
            this.getImage('album');
        },
        //拍照发送
        camera() {
            this.getImage('camera');
        },

        //选照片 or 拍照
        getImage(type) {
            this.hideDrawer();
            uni.chooseImage({
                sourceType: [type],
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                success: res => {
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        uni.getImageInfo({
                            src: res.tempFilePaths[i],
                            success: image => {
                                this.uploadToQiniu(res.tempFilePaths[i], image.width, image.height, 'pic');
                            }
                        });
                    }
                }
            });
        },
        uploadToQiniu(imgPath, width, height, type) {
            var that = this;
            uni.uploadFile({
                url: this.$apis.uploadFile, //仅为示例，非真实的接口地址
                filePath: imgPath,
                name: 'file',
                success: uploadFileRes => {
                    let imgData = JSON.parse(uploadFileRes.data);
                    let imgUrl = this.$mConfig.baseUrl + imgData.message;
                    if (type == 'pic') {
                        let msg = { url: imgUrl, w: width, h: height };
                        that.sendMsg(msg, 'img');
                    } else if (type == 'media') {
                        let msg = {
                            length: 0,
                            url: imgUrl
                        };
                        let min = parseInt(width / 60);
                        let sec = width % 60;
                        min = min < 10 ? '0' + min : min;
                        sec = sec < 10 ? '0' + sec : sec;
                        msg.length = min + ':' + sec;
                        that.sendMsg(msg, 'voice');
                    }
                }
            });
        },
        // 选择表情
        chooseEmoji() {
            this.hideMore = true;
            if (this.hideEmoji) {
                this.hideEmoji = false;
                this.openDrawer();
            } else {
                this.hideDrawer();
            }
        },
        //添加表情
        addEmoji(em) {
            this.textMsg += em.alt;
        },

        //获取焦点，如果不是选表情ing,则关闭抽屉
        textareaFocus() {
            if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
                this.hideDrawer();
            }
        },
        // 发送文字消息
        sendText() {
            uni.hideKeyboard();

            console.log(this.toUserId);

            if (!this.toUserId) {
                uni.showToast({
                    title: '请先选择聊天对象！',
                    icon: 'none'
                });
                return;
            }
            this.hideDrawer(); //隐藏抽屉

            if (!this.textMsg) {
                return;
            }
            let content = this.replaceEmoji(this.textMsg);
            this.sendMsg(content, 'text');
            this.textMsg = ''; //清空输入框

            // 滚动到底部
            var that = this;
            this.$nextTick(function() {
                //进入页面滚动到底部
                that.goToBottom(99999);
                that.$nextTick(function() {
                    that.scrollAnimation = true;
                });
            });
            this.isSpinnerhide = true;
        },
        // 容器滚动到底部
        goToBottom(scrollTop) {
            this.scrollTop = scrollTop + Math.random() * 10;
        },
        //替换表情符号为图片
        replaceEmoji(str) {
            let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
                for (let i = 0; i < this.emojiList.length; i++) {
                    let row = this.emojiList[i];
                    for (let j = 0; j < row.length; j++) {
                        let EM = row[j];
                        if (EM.alt == item) {
                            //在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
                            //比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
                            let onlinePath = this.$mConfig.baseUrl + '/face/emoji/';
                            //let imgstr = '<img src="' + onlinePath + this.onlineEmoji[EM.url] + '">';
                            let imgstr = '<img src="' + onlinePath + EM.url + '">';
                            return imgstr;
                        }
                    }
                }
            });
            return '<div style="display: flex;align-items: center;word-wrap:break-word;flex-wrap: wrap;">' + replacedStr + '</div>';
            //return replacedStr;
        },

        // 添加文字消息到列表
        addTextMsg(msg) {
            if (this.msgList != undefined) this.msgList.push(msg);
        },
        // 添加语音消息到列表
        addVoiceMsg(msg) {
            if (this.msgList != undefined) this.msgList.push(msg);
        },
        // 添加图片消息到列表
        addImgMsg(msg) {
            msg.msg.content = this.setPicSize(msg.msg.content);
            if (this.msgImgList != undefined) this.msgImgList.push(msg.msg.content.url);
            if (this.msgList != undefined) this.msgList.push(msg);
        },
        // 添加系统文字消息到列表
        addSystemTextMsg(msg) {
            if (this.msgList != undefined) this.msgList.push(msg);
        },
        // 预览图片
        showPic(msg) {
            uni.previewImage({
                indicator: 'none',
                current: msg.content.url,
                urls: this.msgImgList
            });
        },
        // 播放语音
        playVoice(msg) {
            this.playMsgid = msg.chatId;
            this.AUDIO.src = msg.content.url;
            this.$nextTick(function() {
                this.AUDIO.play();
            });
        },
        // 录音开始
        voiceBegin(e) {
            if (e.touches.length > 1) {
                return;
            }
            this.initPoint.Y = e.touches[0].clientY;
            this.initPoint.identifier = e.touches[0].identifier;
            this.RECORDER.start({ format: 'mp3' }); //录音开始,
        },
        //录音开始UI效果
        recordBegin(e) {
            this.recording = true;
            this.voiceTis = '松开 结束';
            this.recordLength = 0;
            this.recordTimer = setInterval(() => {
                this.recordLength++;
            }, 1000);
        },
        // 录音被打断
        voiceCancel() {
            this.recording = false;
            this.voiceTis = '按住 说话';
            this.recordTis = '手指上滑 取消发送';
            this.willStop = true; //不发送录音
            this.RECORDER.stop(); //录音结束
        },
        // 录音中(判断是否触发上滑取消发送)
        voiceIng(e) {
            if (!this.recording) {
                return;
            }
            let touche = e.touches[0];
            //上滑一个导航栏的高度触发上滑取消发送
            if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
                this.willStop = true;
                this.recordTis = '松开手指 取消发送';
            } else {
                this.willStop = false;
                this.recordTis = '手指上滑 取消发送';
            }
        },
        // 结束录音
        voiceEnd(e) {
            if (!this.recording) {
                return;
            }
            this.recording = false;
            this.voiceTis = '按住 说话';
            this.recordTis = '手指上滑 取消发送';
            this.RECORDER.stop(); //录音结束
        },
        //录音结束(回调文件)
        recordEnd(e) {
            clearInterval(this.recordTimer);
            if (!this.willStop) {
                this.uploadToQiniu(e.tempFilePath, this.recordLength, 0, 'media');
            }
            this.willStop = false;
        },
        // 切换语音/文字输入
        switchVoice() {
            this.hideDrawer();
            this.isVoice = this.isVoice ? false : true;
        },
        discard() {
            return;
        },
        // 发送消息
        sendMsg(content, type, id = null) {
            var that = this;
            this.userinfo = this.$store.state.userInfo;
            let token = uni.getStorageSync('token');

            if (token) {
                this.$store.commit('SET_TOMSGUSERID', that.toUserId); //被收消息的人
                var sendName = this.userinfo.nickName ? this.userinfo.nickName : this.userinfo.name;

                if (that.toUserId == '') {
                    uni.showToast({
                        title: '请先选择聊天对象',
                        icon: 'none'
                    });
                    return;
                }

                if (this.userinfo.id == that.toUserId) {
                    uni.showToast({
                        title: '不能跟自己聊天',
                        icon: 'none'
                    });
                    return;
                }

                let sendMsg = {
                    type: 'chat',
                    msg: {
                        chatId: Math.floor(Math.random() * 1000 + 1),
                        content: content,
                        from: this.userinfo.id,
                        fromName: sendName,
                        to: `cs_${that.toUserId}`,
                        id: id,
                        type: type,
                        toType: 0 //0单聊  1群聊
                    }
                };

                this.$store.commit('WEBSOCKET_SEND', JSON.stringify(sendMsg)); //发送当前聊天窗口信息

                that.sendMsgloalhost(sendMsg);
            }
        }
    }
};
</script>
<style lang="scss">
.bottom-box {
    height: 250rpx;
}
@import '@../../static/HM-chat/css/style.scss';
.chat-avatar {
    background-size: cover;
    text {
        width: 100%;
        line-height: 50rpx;
        text-align: center;
    }
    position: relative;
    width: 102rpx;
    height: 118rpx;
    line-height: 118rpx;
    text-align: center;
    margin: 0 auto;
    background-size: 102rpx 118rpx;
    overflow: hidden;
    image {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
        width: 102rpx;
        height: 118rpx;
    }
}

page,
.container {
    background: linear-gradient(0deg, #ab61ff, #df61ff);
    background-attachment: fixed;
    width: 100%;
    height: 100%;
}
.content {
    padding: 0 20rpx;
    height: calc(100% - 70px - env(safe-area-inset-bottom));
    .msg-list {
        background: #ffffff;
        border-radius: 16rpx;
        padding-top: 20upx;
        padding-bottom: 20upx;
        height: 100%;
        width: 100%;
        box-sizing: border-box;
    }
}
.detail {
    color: #ff9028;
}
.input-box {
    bottom: 0px;
}
.popup-layer {
    bottom: -312rpx;
}
</style>
